package com.heepay.config;

import com.alibaba.fastjson.JSON;
import com.heepay.service.UserAccountService;
import com.heepay.service.impl.UserAccountServiceImpl;
import com.heepay.util.ApplicationContextUtil;
import com.heepay.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
public class NotifyThread implements Runnable {

    private int count = 1;
    private String notifyUrl;
    private Map<String, Object> paramMap;

    public NotifyThread(){}

    public NotifyThread(String notifyUrl, Map<String, Object> paramMap) {
        this.notifyUrl = notifyUrl;
        this.paramMap = paramMap;
    }

    @Override
    public void run() {
        task();
    }

    private void task() {
        String result = SignUtil.sendRequest(paramMap,notifyUrl);
        log.info(notifyUrl + "：" + result + " count：" + count);
        if(!"success".equals(result)) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //ScheduledTask.queue.offer(new NotifyVo(notifyUrl, paramMap));
            count++;
            if(count <= 3) {
                task();
                log.info("失败重试：" + JSON.toJSONString(this));
            } else {
                UserAccountService userAccountService = ApplicationContextUtil.getBean("UserAccountServiceImpl");
                //重试3次后依然失败，则回滚之前的充值或提现操作
                String resultCode = (String) paramMap.get("resultCode");
                String resultMsg = (String) paramMap.get("resultMsg");
                if ("0001".equals(resultCode) && "充值成功".equals(resultMsg)) {
                    //充值失败，回滚之前的充值操作，即减去对应新增的金额
                    paramMap.put("fetchAmt", paramMap.get("chargeAmt").toString());

                    userAccountService.withdraw(paramMap);
                } else if ("0002".equals(resultCode) && "提现成功".equals(resultMsg)){
                    //提现失败，回滚之前的提现操作，即加上对应减去的金额
                    paramMap.put("chargeAmt", paramMap.get("fetchAmt").toString());
                    userAccountService.recharge(paramMap);
                }
            }
        }
    }
}
